package com.wtwd.campus.utils;

/**
 * @Author ldaoliang
 * @Date create in 13:08 2021/12/6
 * @Description
 */
public class DecoderUtils {

    public static String byte2HexStr(byte buf[]) {
        StringBuffer strbuf = new StringBuffer(buf.length * 2);
        int i;
        for (i = 0; i < buf.length; i++) {
            if (((int) buf[i] & 0xff) < 0x10){
                strbuf.append("0");
            }
            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
        }
        return strbuf.toString();
    }

    public static String checkCode(String para) {
        int length = para.length() / 2;
        String[] dateArr = new String[length];

        for (int i = 0; i < length; i++) {
            dateArr[i] = para.substring(i * 2, i * 2 + 2);
        }
        String code = "00";
        for (int i = 0; i < dateArr.length; i++) {
            code = xor(code, dateArr[i]);
        }
        return hexStringCompleteData(code.toUpperCase(),1);
    }

    // 亦或算法
    private static String xor(String strHex_X,String strHex_Y){
        //将x、y转成二进制形式
        String anotherBinary=Integer.toBinaryString(Integer.valueOf(strHex_X,16));
        String thisBinary=Integer.toBinaryString(Integer.valueOf(strHex_Y,16));
        String result = "";
        //判断是否为8位二进制，否则左补零
        if(anotherBinary.length() != 8){
            for (int i = anotherBinary.length(); i <8; i++) {
                anotherBinary = "0"+anotherBinary;
            }
        }
        if(thisBinary.length() != 8){
            for (int i = thisBinary.length(); i <8; i++) {
                thisBinary = "0"+thisBinary;
            }
        }
        //异或运算
        for(int i=0;i<anotherBinary.length();i++){
            //如果相同位置数相同，则补0，否则补1
            if(thisBinary.charAt(i)==anotherBinary.charAt(i)){
                result+="0";
            }
            else{
                result+="1";
            }
        }
        return Integer.toHexString(Integer.parseInt(result, 2));
    }

    public static String hexStringCompleteData(String str, int byteNum) {
        if (byteNum == 1) {
            if (str.length() == 1) {
                str = "0" + str;
            }
        } else if (byteNum == 2) {
            if (str.length() == 1) {
                str = "000" + str;
            } else if (str.length() == 2) {
                str = "00" + str;
            } else if (str.length() == 3) {
                str = "0" + str;
            }
        }
        return str.toUpperCase();
    }
}
